package com.zzyl.nursing.service.impl;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONUtil;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.iot.IotMsgNotifyData;
import com.zzyl.nursing.dto.DeviceDataDto;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author zhangshiyu
 * @date 2025-09-23
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceDataDto dto)
    {
        return deviceDataMapper.selectDeviceDataList(dto);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    @Autowired
    private IDeviceService deviceService;
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData dto) {
        //通过设备id查询设备
        String deviceId = dto.getHeader().getDeviceId();
        Device device = deviceService.lambdaQuery()
                .eq(Device::getIotId, deviceId)
                .one();
        if(device==null){
            return;
        }
        //不存在return;

        //存在就构建设备数据，添加到集合中
//        DeviceData deviceData = new DeviceData();
        List<DeviceData> list = new ArrayList<>();
//        String serviceId = dto.getBody().getServices().get(0).getServiceId();
        String eventTime = dto.getBody().getServices().get(0).getEventTime();


//        String originalTime = "20250217T083248Z";


// 自定义 DateTimeFormatter 来解析 "20250923T124853Z" 格式
        DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX");

// 解析原始时间字符串为 Instant
        Instant instant = null;
        try {
            OffsetDateTime offsetDateTime = OffsetDateTime.parse(eventTime, customFormatter);
            instant = offsetDateTime.toInstant();
        } catch (DateTimeParseException e) {
            log.error("时间字符串解析失败: " + eventTime, e);
            instant = Instant.now(); // 或其他默认处理方式
        }

// 转换为东八区(Asia/Shanghai)的 LocalDateTime
        ZoneId eastEightZone = ZoneId.of("Asia/Shanghai");
        LocalDateTime eastEightLdt = LocalDateTime.ofInstant(instant, eastEightZone);

// 此时得到的就是东八区的 LocalDateTime 对象
        System.out.println("东八区 LocalDateTime: " + eastEightLdt);
        System.out.println("类型验证: " + (eastEightLdt instanceof LocalDateTime));








        Map<String, Object> properties = dto.getBody().getServices().get(0).getProperties();
        properties.forEach((k,v)->{
            DeviceData deviceData = new DeviceData();
            deviceData.setDeviceName(device.getDeviceName());
            deviceData.setIotId(device.getIotId());
            deviceData.setProductKey(device.getProductKey());
            deviceData.setProductName(device.getProductName());
            deviceData.setFunctionId(k);
            //接入的位置
            deviceData.setAccessLocation(device.getRemark());
            deviceData.setLocationType(device.getLocationType());

            deviceData.setDeviceDescription(device.getDeviceDescription());
            deviceData.setDataValue(v+"");
            deviceData.setAlarmTime(eastEightLdt);

            deviceData.setPhysicalLocationType(device.getPhysicalLocationType());
            deviceData.setCreateTime(device.getCreateTime());
            deviceData.setUpdateTime(device.getUpdateTime());
            deviceData.setCreateBy(device.getCreateBy());
            deviceData.setUpdateBy(device.getUpdateBy());
            deviceData.setRemark(device.getRemark());
            list.add(deviceData);
        });


        //将集合数据批量保存到数据库
        saveBatch(list);

        //将数据添加到redis中
        //1类型Hash 2key名
//        redisTemplate.opsForHash().put(Constants.IOT_DEVICE_DATA,deviceId, JSONUtil.toJsonStr(list));
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_DATA,deviceId,JSONUtil.toJsonStr(list));
    }
}
